<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { useUserStoreHook } from "@/store/modules/user";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getMySubmissionStatisticsApi,
  type SubmissionStatisticsDTO
} from "@/api/performance/statistics";
import {
  Document,
  Upload,
  Checked,
  DataAnalysis
} from "@element-plus/icons-vue";

defineOptions({
  name: "Welcome"
});

const router = useRouter();
const userStore = useUserStoreHook();
const currentUserInfo = computed(() => userStore?.currentUserInfo);
const currentRoleId = computed(() => currentUserInfo.value?.roleId as number | undefined);

// 当前考核年度
const currentYear = computed(() => new Date().getFullYear());

// 个人信息完整性检查
const isProfileComplete = computed(() => {
  const user = currentUserInfo.value;
  // 检查真实姓名（可能是nickName或nickname）
  const hasNickName = !!(user?.nickName || (user as any)?.nickname);
  return !!(
    hasNickName &&
    user?.phoneNumber &&
    user?.deptId
  );
});

// 加载状态
const loading = ref(false);

// 统计数据
const myStatistics = ref<SubmissionStatisticsDTO | null>(null);

// 主类别列表
const mainCategories = [
  "教研工作量",
  "科研工作量",
  "育人工作量",
  "服务工作量",
  "其他工作量"
];

// 状态列表
const statusList = [
  { key: "DRAFT", label: "草稿", color: "#909399" },
  { key: "PENDING_AUDIT", label: "待审核", color: "#E6A23C" },
  { key: "REJECTED", label: "已驳回", color: "#F56C6C" },
  { key: "APPROVED", label: "已通过", color: "#67C23A" }
];


// 快捷操作按钮配置
const quickActions = [
  {
    key: "submission",
    label: "个人项目上报",
    icon: Document,
    routeName: "submissionList"
  },
  {
    key: "teaching",
    label: "教学工作量导入",
    icon: Upload,
    routeName: "teachingList"
  },
  {
    key: "audit",
    label: "材料审核",
    icon: Checked,
    routeName: "submissionReview"
  },
  {
    key: "score",
    label: "分数总览",
    icon: DataAnalysis,
    routeName: "userScoreRecordList"
  }
];

// 检查按钮权限
const canClickButton = (buttonKey: string): boolean => {
  const roleId = currentRoleId.value;
  if (!roleId) return false;

  switch (buttonKey) {
    case "submission":
      // 所有角色都可以点击项目上报
      return true;
    case "teaching":
      // roleId=1,6,7,8,15,16 可以点击
      return [1, 6, 7, 8, 15, 16].includes(roleId);
    case "audit":
      // roleId=1,3,4,5,6,7,8,15 可以点击
      return [1, 3, 4, 5, 6, 7, 8, 15].includes(roleId);
    case "score":
      // roleId=1,6,7,8,15 可以点击
      return [1, 6, 7, 8, 15].includes(roleId);
    default:
      return false;
  }
};

// 处理快捷操作按钮点击
const handleQuickAction = (buttonKey: string, routeName: string) => {
  // 检查个人信息完整性
  if (!isProfileComplete.value) {
    ElMessageBox.confirm(
      "需要先补充个人信息才能使用此功能，是否前往个人中心？",
      "提示",
      {
        confirmButtonText: "前往",
        cancelButtonText: "取消",
        type: "warning"
      }
    )
      .then(() => {
        router.push("/global/user/profile");
      })
      .catch(() => {});
    return;
  }

  // 检查权限
  if (!canClickButton(buttonKey)) {
    ElMessage.warning("您没有权限访问此功能");
    return;
  }

  // 跳转到对应页面
  router.push({ name: routeName });
};

// 获取统计数据
const fetchStatistics = async () => {
  try {
    loading.value = true;

    // 获取本人统计数据
    const { data: myData } = await getMySubmissionStatisticsApi();
    myStatistics.value = myData || null;
  } catch (error) {
    console.error("获取统计数据失败:", error);
    ElMessage.error("获取统计数据失败");
  } finally {
    loading.value = false;
  }
};


// 计算各主类别的项目总数
const getCategoryTotalCount = (category: string): number => {
  if (!myStatistics.value?.projectCountByCategoryAndStatus) return 0;
  const categoryData = myStatistics.value.projectCountByCategoryAndStatus[category];
  if (!categoryData) return 0;
  let total = 0;
  Object.values(categoryData).forEach(count => {
    total += count || 0;
  });
  return total;
};

// 计算各主类别的总分数
const getCategoryTotalScore = (category: string): number => {
  if (!myStatistics.value?.scoreInfo) return 0;
  const scoreInfo = myStatistics.value.scoreInfo;
  switch (category) {
    case "教研工作量":
      return scoreInfo.teachingWorkload || 0;
    case "科研工作量":
      return scoreInfo.researchWorkload || 0;
    case "育人工作量":
      return scoreInfo.educationWorkload || 0;
    case "服务工作量":
      return scoreInfo.serviceWorkload || 0;
    case "其他工作量":
      return scoreInfo.otherWorkload || 0;
    default:
      return 0;
  }
};

// 计算教学得分总数
const getTeachingTotalScore = (): number => {
  if (!myStatistics.value?.scoreInfo) return 0;
  const scoreInfo = myStatistics.value.scoreInfo;
  return (scoreInfo.generalCourseScore || 0) + 
         (scoreInfo.majorCourseScore || 0) + 
         (scoreInfo.labCourseScore || 0);
};

onMounted(() => {
  fetchStatistics();
});
</script>

<template>
  <div class="welcome-container" v-loading="loading">
    <!-- 个人信息提示 -->
    <el-alert
      v-if="!isProfileComplete"
      title="请先完善个人信息"
      type="warning"
      :closable="false"
      show-icon
      class="mb-4"
    >
      <template #default>
        <span>您的个人信息不完整，请前往</span>
        <el-link
          type="primary"
          :underline="false"
          @click="router.push('/global/user/profile')"
          class="mx-1"
        >
          个人中心
        </el-link>
        <span>补充真实姓名、手机号码和部门信息</span>
      </template>
    </el-alert>

    <!-- 用户信息和考核年度卡片 -->
    <el-row :gutter="24" class="mb-4">
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>当前考核年度</span>
            </div>
          </template>
          <div class="text-center">
            <div class="text-4xl font-bold text-primary">{{ currentYear }}</div>
            <div class="text-sm text-gray-500 mt-2">年度</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>用户信息</span>
            </div>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="用户名称">
              {{ currentUserInfo?.username || "-" }}
            </el-descriptions-item>
            <el-descriptions-item label="手机号码">
              {{ currentUserInfo?.phoneNumber || "-" }}
            </el-descriptions-item>
            <el-descriptions-item label="部门">
              {{ currentUserInfo?.deptName || "-" }}
            </el-descriptions-item>
            <el-descriptions-item label="角色">
              {{ currentUserInfo?.roleName || "-" }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>
    </el-row>

    <!-- 快捷操作按钮 -->
    <el-card shadow="hover" class="mb-4">
      <template #header>
        <div class="card-header">
          <span>快捷操作</span>
        </div>
      </template>
      <el-row :gutter="24">
        <el-col
          v-for="action in quickActions"
          :key="action.key"
          :xs="12"
          :sm="6"
          :md="6"
        >
          <div
            class="quick-action-item"
            :class="{ disabled: !canClickButton(action.key) }"
            @click="handleQuickAction(action.key, action.routeName)"
          >
            <el-icon :size="40" class="action-icon">
              <component :is="action.icon" />
            </el-icon>
            <div class="action-label">{{ action.label }}</div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 本人得分详情和项目数量统计 -->
    <el-row :gutter="24" class="mb-4">
      <!-- 项目数量统计卡片 -->
      <el-col :span="24">
        <el-card shadow="hover" class="mb-4">
          <template #header>
            <div class="card-header">
              <span>本人已通过的分数统计</span>
            </div>
          </template>
          <el-row :gutter="16">
            <el-col
              v-for="category in mainCategories"
              :key="category"
              :xs="24"
              :sm="12"
              :md="8"
              :lg="4"
            >
              <el-card shadow="never" class="category-card">
                <div class="category-title">{{ category }}</div>
                <div class="category-total">总数: {{ getCategoryTotalCount(category) }}</div>
                <div class="category-details">
                  <div
                    v-for="status in statusList"
                    :key="status.key"
                    class="status-item"
                  >
                    <span
                      class="status-dot"
                      :style="{ backgroundColor: status.color }"
                    ></span>
                    <span class="status-label">{{ status.label }}:</span>
                    <span class="status-count">
                      {{
                        myStatistics?.projectCountByCategoryAndStatus?.[category]?.[status.key] || 0
                      }}
                    </span>
                  </div>
                </div>
                <div class="category-score">
                  得分: {{ getCategoryTotalScore(category).toFixed(2) }}
                </div>
              </el-card>
            </el-col>
            <!-- 教学得分卡片 -->
            <el-col
              :xs="24"
              :sm="12"
              :md="8"
              :lg="4"
            >
              <el-card shadow="never" class="category-card">
                <div class="category-title">教学得分</div>
                <div class="category-total">总分数: {{ getTeachingTotalScore().toFixed(2) }}</div>
                <div class="category-details">
                  <div class="status-item">
                    <span class="status-dot" style="background-color: #409EFF"></span>
                    <span class="status-label">通用课程分数:</span>
                    <span class="status-count">
                      {{ (myStatistics?.scoreInfo?.generalCourseScore || 0).toFixed(2) }}
                    </span>
                  </div>
                  <div class="status-item">
                    <span class="status-dot" style="background-color: #67C23A"></span>
                    <span class="status-label">专业课程分数:</span>
                    <span class="status-count">
                      {{ (myStatistics?.scoreInfo?.majorCourseScore || 0).toFixed(2) }}
                    </span>
                  </div>
                  <div class="status-item">
                    <span class="status-dot" style="background-color: #E6A23C"></span>
                    <span class="status-label">实验课程分数:</span>
                    <span class="status-count">
                      {{ (myStatistics?.scoreInfo?.labCourseScore || 0).toFixed(2) }}
                    </span>
                  </div>
                </div>
                <div class="category-score">
                  总得分: {{ getTeachingTotalScore().toFixed(2) }}
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-card>
      </el-col>

    </el-row>
  </div>
</template>

<style lang="scss" scoped>
.welcome-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.quick-action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  min-height: 120px;

  &:hover:not(.disabled) {
    border-color: var(--el-color-primary);
    background-color: var(--el-color-primary-light-9);
    transform: translateY(-4px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }

  &.disabled {
    cursor: not-allowed;
    opacity: 0.5;
    background-color: #f5f7fa;
  }

  .action-icon {
    color: var(--el-color-primary);
    margin-bottom: 12px;
  }

  .action-label {
    font-size: 14px;
    color: #606266;
    text-align: center;
  }
}

.category-card {
  margin-bottom: 16px;
  height: 100%;

  :deep(.el-card__body) {
    display: flex;
    flex-direction: column;
    min-height: 280px;
  }

  .category-title {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 12px;
    color: #303133;
  }

  .category-total {
    font-size: 18px;
    font-weight: 600;
    color: var(--el-color-primary);
    margin-bottom: 12px;
  }

  .category-details {
    margin-bottom: 12px;
    flex: 1;

    .status-item {
      display: flex;
      align-items: center;
      margin-bottom: 8px;
      font-size: 14px;

      .status-dot {
        width: 8px;
        height: 8px;
        border-radius: 50%;
        margin-right: 8px;
      }

      .status-label {
        color: #606266;
        margin-right: 8px;
      }

      .status-count {
        font-weight: 600;
        color: #303133;
      }
    }
  }

  .category-score {
    font-size: 16px;
    font-weight: 600;
    color: #67c23a;
    padding-top: 12px;
    border-top: 1px solid #e4e7ed;
    margin-top: auto;
  }
}
</style>
